from django.utils.deprecation import MiddlewareMixin
from sa import models
from django.shortcuts import redirect
# 导入白名单
from django.conf import settings
from django.urls import reverse
from Utils import encrypt
from django.http import Http404


class AuthMiddleware(MiddlewareMixin):
    def process_request(self, request):
        # 检查是否应该跳过此中间件的逻辑
        if request.path.startswith('/admin') or request.path_info in settings.WHITE_REGEX_URL_LIST:
            return None
        emp_no = request.session.get('user_EmpNo', None)
        if emp_no is None:
            return redirect('user_login')
        try:
            sa_obj = models.SA_Info.objects.get(Employee_No=emp_no)
        except models.SA_Info.DoesNotExist:
            # except Exception as e:
            return redirect('user_login')
        request.sa = sa_obj
        print(f'当前登录的用户是：{request.sa.SA_CName}')

    # 先执行 process_request， 再执执行 urls路由， 再执行 process_view
    def process_view(self, request, view_func, view_args, view_kwargs):
        """
        :param self: 指向中间件实例本身的引用
        :param request: HttpRequest对象，表示当前的请求
        :param view_func: 即将调用的视图函数。注意，这只是一个函数对象，而不是函数调用的结果
        :param view_args: 一个列表，包含将要传递给视图函数的位置参数。。
        :param view_kwargs: 是一个字典，它包含了URLconf中定义的、将传递给视图函数的所有关键字参数。
        这些参数通常是通过URL中的路径转换器（如<int:p_id>从URL模式中提取出来的。)
        :return:
        """
        if request.path_info.startswith('/project/'):
            p_id = view_kwargs.get('p_id')
            if p_id is None:
                return redirect('my_project_list')
            else:
                try:
                    project_obj = models.Project.objects.get(id=p_id, actors=request.sa)
                    request.project = project_obj
                    print(f'当前选中的项目是：{request.project.customer}')
                except Exception as e:
                    print(e)
                    return redirect('my_project_list')
        # if request.path_info.startswith('/center/'):
        #     p_id = view_kwargs.get('p_id')
        #     if p_id is None:
        #         return redirect('center_platform')
        #         # raise Http404("项目 ID 未提供或无效。")
        #     else:
        #         try:
        #             project_obj = models.Project.objects.get(id=p_id)
        #             request.project = project_obj
        #             print(f'当前选中的项目是：{request.project.customer}')
        #         except Exception as e:
        #             print(e)
        #             return redirect('center_platform')
